package com.gupaoedu.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 *
 * @Date: 2019/7/13 14:42
 */
public class CuratorDemo {

    private static  String CONN = "192.168.150.130:2181,192.168.150.131:2181,192.168.150.132:2181";

    public static void main(String[] args) throws Exception {

        //创建连接，可以new 也可以基于流式风格build
//        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient();
        CuratorFramework curatorFramework =
                CuratorFrameworkFactory.builder().connectString(CONN)
                        //客户端 服务端之间会话的超时时间，设置一下
                        .sessionTimeoutMs(5000)
                        //连接失败的时候，重试机制，设置一下。每睡1s去重试一次，最多试3次，每次的睡眠时间递增
                        /**重试策略：1、衰减重试（或递增重试）ExponentialBackoffRetry
                         * 2、只试一次。具体见老师笔记
                         */
                .retryPolicy(new ExponentialBackoffRetry(1000,3)).build();

        curatorFramework.start();
//        curatorFramework.sync().forPath()
//        createData(curatorFramework);
        updateData(curatorFramework);
        //连完了，就操作撒，无非就是CRUD。
    }

    //creatingParentContainersIfNeeded递归创建
    private static void createData(CuratorFramework curatorFramework) throws Exception {
        curatorFramework.create().creatingParentContainersIfNeeded()
                .withMode(CreateMode.PERSISTENT).forPath("/data/program","test".getBytes());
    }

    private static void updateData(CuratorFramework curatorFramework) throws Exception {
        //zk做配置中心的时候，value值是经常被修改的
        curatorFramework.setData().forPath("/data/program","up".getBytes());

    }

    //递归删除
    private static void deleteData(CuratorFramework curatorFramework) throws Exception {
        Stat stat=new Stat();
        String value=new String(curatorFramework.getData().storingStatIn(stat).forPath("/data/program"));
        //先用stat去拿到版本号，再用版本号去删除
        curatorFramework.delete().withVersion(stat.getVersion()).forPath("/data/program");
    }

}
